const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.get('/', (req, res, next) => {
  const reg = new RegExp(req.query.keyword);
  User.estimatedDocumentCount({
    $or: [
      { username: { $regex: reg }},
      { name: { $regex: reg }}
    ]
  })
    .then(count => {
      User.find({
        $or: [
          { username: { $regex: reg }},
          { name: { $regex: reg }}
        ]
      })
        .skip(parseInt(req.query.offset))
        .limit(parseInt(req.query.limit))
        .then(users => {
          res.send({
            list: users,
            count
          })
        })
        .catch(err => {
          next(err);
        })
    })
    .catch(err => {
      next(err);
    })
})
router.post('/', (req, res, next) => {
  User.create(req.body)
    .then(user => {
      res.json(user);
    })
    .catch(err => {
      next(err)
    })
})
router.put('/:id', (req, res, next) => {
  User.findOneAndUpdate({
    _id: req.params.id
  }, {
    $set: {
      name: req.body.name,
      phone: req.body.phone,
      sex: req.body.sex
    }
  }, {
    new: true
  })
    .then(user => res.json(user))
    .catch(err => next(err));
})
router.delete('/:id', (req, res, next) => {
  User.findOneAndRemove({
    _id: req.params.id
  })
    .then(() => res.send())
    .catch(err => next(err))
})
module.exports = router;